from functools import wraps
from flask import request, jsonify, current_app
from app.models import User

def get_current_user():
    """从请求头中获取当前用户"""
    auth_header = request.headers.get('Authorization')
    if not auth_header or not auth_header.startswith('Bearer '):
        return None

    token = auth_header.split(' ')[1]
    return User.verify_token(token, current_app.config['SECRET_KEY'])

def require_auth(f):
    """认证装饰器"""
    @wraps(f)
    def decorated_function(*args, **kwargs):
        user = get_current_user()
        if not user:
            return jsonify({
                'code': 401,
                'message': '请先登录'
            }), 401

        # 将用户对象传递给视图函数
        return f(user, *args, **kwargs)

    return decorated_function

def optional_auth(f):
    """可选认证装饰器"""
    @wraps(f)
    def decorated_function(*args, **kwargs):
        user = get_current_user()
        # 将用户对象传递给视图函数（可能为None）
        return f(user, *args, **kwargs)

    return decorated_function

def verify_chart_ownership(user, chart_id):
    """验证用户是否拥有指定的图表"""
    from app.models import Chart
    if not chart_id:
        return False
    chart = Chart.query.filter_by(id=chart_id, user_id=user.id).first()
    return chart is not None